import { ref, reactive, computed, watch, getCurrentInstance } from '@vue/composition-api'
import { getUserProjectList } from '@/api/createFilingMessage'
import { getRoleByProject } from '@/api/user'

let projectList = null

export function getProductList () {
  getUserProjectList()
    .then(result => { projectList.value = result })
}

export function useProjectList () {
  if (!projectList) {
    projectList = ref([])
    getProductList()
  }
  return projectList
}

export function useProjectSelectOption (isShowAll = true) {
  const projectList = useProjectList()

  const projectSelectOption = computed(() => {
    const list = []
    if (isShowAll) {
      list.push({
        label: '全部',
        value: '',
      })
    }

    projectList.value.forEach(item => {
      list.push({
        label: item.name,
        value: item.projectId,
      })
    })
    return list
  })

  return projectSelectOption
}

const defaultMenu = [
  {
    title: '订单报备',
    icon: 'el-icon-document-add',
    url: '/customer/report/index',
    powerLabel: 'dingdanbaobei',
  },
  {
    title: '商品上架',
    icon: 'el-icon-document-add',
    url: '/customer/report/goods',
    // disabled: true,
    powerLabel: 'shangpinbaobei',
  },
  {
    title: '项目信息',
    icon: 'el-icon-s-order',
    url: '/customer/projectInfo',
    // disabled: true,
    powerLabel: 'xiangmuxinxi',
  },
  {
    title: '资质证书',
    icon: 'el-icon-document-add',
    url: '/customer/certificate',
    powerLabel: 'zizhizhengshu',
  },
]

let gState = null

export function useProjectCustomerSetting () {
  const projectSelectOption = useProjectSelectOption(false)

  if (!gState) {
    gState = reactive({
      projectId: ~~localStorage.getItem('ProjectCustomerSettingProjectId') || null, // 当前选中
      projectName: null,
      power: [],
    })
  }
  const state = gState

  const setProjectId = (value) => {
    state.projectId = ~~value
    for (const item of projectSelectOption.value) {
      // console.log(item.value, state.projectId)
      if (item.value === state.projectId) {
        state.projectName = item.label
        break
      }
    }
    // eslint-disable-next-line no-return-assign
    getRoleByProject(value).then(result => state.power = result)
    localStorage.setItem('ProjectCustomerSettingProjectId', value)
  }

  watch(projectSelectOption, (data) => {
    if (data.length) {
      let projectId = state.projectId
      if (projectId) {
        const project = data.find(item => item.value === state.projectId)
        if (!project) {
          projectId = null
        }
      }
      if (!projectId) {
        projectId = data[0].value
      }
      setProjectId(projectId)
    }
  }, { immediate: true })

  const menu = computed(() => {
    return defaultMenu.filter(item => {
      return !!state.power.find(power => item.powerLabel === power.label)
    })
  })

  return {
    projectSelectOption,
    state,
    menu,
    setProjectId,
  }
}
